<template>
	<view class="u-page">
		
				<u-navbar back-text=""
				:leftIconColor="tksetting.titlecolor" 
				:bgColor="tksetting.color" 
				:titleStyle="{color:tksetting.titlecolor}" 
				:title="title"  
				:autoBack="true"  
				:placeholder="true">
				</u-navbar>
		
				<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
				<u--form
					labelPosition="top"
					:model="model1"
					labelWidth	="200"
					:labelStyle="labelStyle"
					ref="form1"
				>
				
				<u-form-item
					label="请选择你所在城市"
					prop="userInfo.address"
					borderBottom
					ref="item1"
					:required="true"
				>
					<u--input
						v-model="address_name"
						border="none"
						:readonly="true"
						placeholder="请选择所在城市"
					></u--input>
					
					<u-button
						slot="right"
						text="选择"
						type="success"
						size="small"
						@click="classshow=true"
					></u-button>
					
				</u-form-item>
				
					<!-- 只在微信小程序编译 -->
					<!-- #ifdef MP-WEIXIN -->
					
					<!-- <u-form-item
						label="昵称"
						prop="userInfo.name"
						borderBottom
						ref="item1"
						:required="true"
					>
					
						<u--input
						    type="nickname"
							@blur="bindblur" @change="bingchange" 
							:focus="name_force"
							v-model="model1.userInfo.name"
							border="none"
							placeholder="请输入昵称"
						></u--input>
					</u-form-item>
					
					<u-form-item
						label="头像"
						prop="userInfo.pic"
						borderBottom
						ref="item1"
						:required="true"
					>
										
						  <view style="width: 160rpx">
							  <button   type="balanced" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
									<image :src="model1.userInfo.pic" style="width: 100rpx;height: 100rpx;"></image>
							  </button>
						  </view>
					</u-form-item> -->
					
					
					<u-form-item
						label="登录账号"
						prop="userInfo.tel"
						borderBottom
						ref="item1"
						:required="true"
					>
						<u--input
							v-model="model1.userInfo.tel"
							border="none"
							:readonly="true"
							placeholder="11位手机号码"
						></u--input>
						
						<u-button
						    ref="phoneBtn"
							slot="right"
							open-type="getPhoneNumber"   @getphonenumber="getPhoneNumber" 
							text="手机号快捷登录"
							type="success"
							size="small"
						></u-button>
						
					</u-form-item>
					<!-- #endif -->
					
				   <!-- #if H5 -->	
				   
				   <u-form-item
				   	label="登录账号"
				   	prop="userInfo.tel"
				   	borderBottom
				   	ref="item1"
				   	:required="true"
				   >
				   	<u--input
				   		v-model="model1.userInfo.tel"
				   		border="none"
				   		placeholder="11位手机号码"
				   	></u--input>
				   </u-form-item>
				   
				   
				   <u-form-item
				   	label="图形验证"
				   	prop="imgcode"
				   	labelWidth="80"
				   	borderBottom
				   	:required="true"
				   >
				   	<u--input
				   		v-model="model1.imgcode"
				   		border="none"
				   		placeholder="请填写图形验证码"
				   		maxlength="4"
				   	></u--input>
				   	<view  slot="right" class="code-img-wrapper" @click="updateImageCode">
				   	  <canvas style="width:220rpx;height:86rpx;" canvas-id="canvas"></canvas>
				   	</view>
				   
				   </u-form-item>
				   
				   <u-form-item
				   	label="短信验证"
				   	prop="userInfo.code"
				   	labelWidth="80"
				   	borderBottom
				   >
				   	<u--input
				   		v-model="model1.userInfo.code"
				   		border="none"
				   		placeholder="请填写短信验证码"
				   	></u--input>
				   	<u-button
				   		slot="right"
				   		@tap="getCode"
				   		:text="tips"
				   		type="success"
				   		size="mini"
				   		:disabled="disabled1"
				   	></u-button>
				   </u-form-item>
				   
				   
				   <!-- #endif -->
				   
				   
				    <!-- #if APP-PLUS -->
					
					<u-form-item
						label="登录账号"
						prop="userInfo.user"
						borderBottom
						ref="item1"
						:required="true"
					>
						<u--input
							v-model="model1.userInfo.user"
							border="none"
							placeholder="登录账号以字母开头"
						></u--input>
					</u-form-item>
				   					
					<!-- #endif -->
					
					
					<u-form-item
						label="登录密码"
						prop="userInfo.passwd"
						borderBottom
						ref="item1"
						:required="true"
					>
						<u--input
							v-model="model1.userInfo.passwd"
							border="none"
							type="password"
							placeholder="请输入密码"
						></u--input>
					</u-form-item>
					
					<u-form-item
						label="重复密码"
						prop="confirm_passwd"
						borderBottom
						ref="item1"
						:required="true"
					>
						<u--input
							v-model="model1.confirm_passwd"
							border="none"
							type="password"
							placeholder="请重复输入密码"
							ref="cf"
						></u--input>
					</u-form-item>
					
					<!-- #if APP-PLUS -->
					<u-form-item
						label="图形验证"
						prop="imgcode"
						labelWidth="80"
						borderBottom
						:required="true"
					>
						<u--input
							v-model="model1.imgcode"
							border="none"
							placeholder="请填写图形验证码"
							maxlength="4"
						></u--input>
						<view  slot="right" class="code-img-wrapper" @click="updateImageCode">
						  <canvas style="width:220rpx;height:86rpx;" canvas-id="canvas"></canvas>
						</view>
					
					</u-form-item>
									
					<!-- #endif -->
					
					
					
				</u--form>
				
				<view style="padding: 12rpx 0; text-align: center;color: #ccc;">
					<text style="color: #ccc;" @click="routs('yhxy')">用户协议</text>
					<text style="margin: 0 24rpx;"> | </text>
					<text style="color: #ccc;" @click="routs('ysxy')">隐私协议</text>
				</view>
				<view style="padding: 12rpx 0; display: flex;justify-content: center;">
					<u-checkbox-group
					            v-model="xieyi"
					            placement="column"
					            @change="xieyi_check"
					        >
					            <u-checkbox
					                label="我同意以上协议"
					                name="1"
									:activeColor="tksetting.color"
					            >
					            </u-checkbox>
					</u-checkbox-group>
					
				</view>
				
				<u-button
					type="primary"
					text="立即注册"
					customStyle="margin-top: 50px"
					:disabled="ti_status"
					@click="submit"
					:color="tksetting.color"
				>
				</u-button>
			
				<u-picker 
				title="请选择报考地区"
				keyName="label"
				:show="showarea"
				:columns="arealist"
				@confirm="confirm"
				@cancel="showarea=false"
				>
				</u-picker>
				
				<u-code
					ref="uCode"
					@change="codeChange"
					seconds="20"
					@start="disabled1 = true"
					@end="disabled1 = false"
				>
				</u-code>
				
				<u-picker
					:show="classshow"
					@cancel="classshow=false"
					@close="classshow=false" ref="uPicker" @confirm="confirm_xf" :loading="classloading" :columns="columns" keyName="label" @change="changeHandler">
				</u-picker>
		
	</view>
</template>

<script>
import {toast,wxcode,clearStorageSync, setStorageSync, getStorageSync, useRouter,checklogin} from '@/utils/utils.js'
import { Mcaptcha  } from '@/utils/mcaptcha'
import { mapState } from 'vuex';
import BASE_URL from '@/api/env.js' //引入接口共用地址
	export default {
		data() {
			return {
				title:'账号注册',
				address_name:'',
				classshow: false,
				classloading: false,
				columns: [],
				
				name_force:false,
				ti_status:false,
				labelStyle:{"font-weight":600},
				fileList1: [],
				fileList2: [],
				
				mcaptcha:'',
				disabled1: false,
				xieyi:[],
				tips: '',
				value: '',
				showCalendar: false,
				showBirthday: false,
				session_ke:'',
				areaname:'',
				model1: {
					    userInfo: {
							name: '',
							user:'',
							tel: '',
							passwd:'',
							openid:'',
							address:'',
							area:'',
							code:'',
							mypid:'',
							pic:'',
					},
					code: '',
					imgcode:'',
					confirm_passwd:''
				},
				showSex: false,
				showarea:false,
				birthday: Number(new Date()),
				arealist: [],
				rules: {
					'userInfo.tel': [{
						type: 'string',
						required: true,
						message: '请填手机号',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						message: "请正确输入手机号格式",
						// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						trigger: ["change", "blur"],
					}],
					'userInfo.code': {
						type: 'string',
						required: true,
						len: 4,
						message: '请填写4位验证码',
						trigger: ['blur']
					},
					'userInfo.pic': {
						type: 'string',
						required: true,
						message: '请上传头像',
						trigger: ['blur']
					},
					'userInfo.name': {
						type: 'string',
						required: true,
						message: '请输入昵称',
						trigger: ['blur']
					},
					'userInfo.address': {
						type: 'string',
						required: true,
						message: '请选择您所在城市',
						trigger: ['blur']
					},
					'userInfo.passwd': {
						type: 'string',
						required: true,
						min:6,
						message: '请输入6位以上密码',
						trigger: ['blur']
					},
					confirm_passwd:[{
						type: 'string',
						message: '请重复输入密码',
						trigger: ['blur']
					},
					{
						validator: (rule, value, callback) => {
							if (value != this.model1.userInfo.passwd) {
							   return false;
							}else{
							   return true;
							}
						},
						message: '两次密码不一样',
						// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						trigger: ["blur","change"],
					}],
					imgcode:[{
						type: 'string',
						required:true,
						message: '请输入图形验证码',
						trigger: ['blur']
					},
					{
						validator: (rule, value, callback) => {
							let validate = this.mcaptcha.validate(value)
							return validate?true:false;
						},
						message: '验证码不正确',
						// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						trigger: ["blur","change"],
					}],
					'userInfo.user': [{
						type: 'string',
						required: true,
						message: '请输入登录账号',
						trigger: ['blur']
					},
					{
						validator: (rule, value, callback) => {
							const reg = /^[a-zA-Z][a-zA-Z0-9_]*$/;
							return reg.test(value)?true:false;
						},
						message: '账号必须以字母开头，仅含字母、数字或下划线',
						// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						trigger: ["blur","change"],
					}
					],
				},
			}
		},
		async onLoad(opt) {
			
			
			// #ifdef MP-WEIXIN
			   const data= await wxcode();
			   const wx_info=await this.$api.wxlogin({code:data.code})
			   const openids=JSON.parse(wx_info.data[1]);
			   console.log(openids)
			   if(openids.errcode){
				   toast('小程序获取信息失败')
			   }else{
				   this.session_ke=openids.session_key;
				   this.model1.userInfo.openid=openids.openid
			   }
			// #endif
			this.check_reg();
			
			this.cat_xf();
			
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules);
			this.mcaptcha = new Mcaptcha({
			     el: 'canvas',
			     width: 80,
			     height: 35,
			     createCodeImg: ""
			   });
			   
			
			   
		},
		onShow() {
			
		},
		computed:{
			...mapState(['tksetting','mypid'])
		},
		methods: {
			
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
					
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
						console.log(value[0].id)
						this.$api.citys({pid:value[0].id}).then(res => {
							picker.setColumnValues(1, res.data)
						})
				}
			},
			async cat_xf(){
					  const xf=await this.$api.citys();
					 
					  const xf_x=await this.$api.citys({pid:xf.data[0].id});
					   console.log(xf_x)
					  this.columns=[xf.data,xf_x.data];
					  
			},
			confirm_xf(e){
				this.classshow=false;
				
				this.address_name=e.value[1].label
				this.model1.userInfo.area=e.value[0].id
				this.model1.userInfo.address=e.value[1].id
			},
			
			async onChooseavatar(e) {
			const pic= await this.uploadFilePromise(e.detail.avatarUrl)
			console.log()
			this.model1.userInfo.pic =pic;
			this.name_force=true;
		},
		    bindblur(e) {
				console.log(e)
				this.model1.userInfo.name = e// 获取微信昵称
			},
			bingchange(e){
				console.log(e)
				this.model1.userInfo.name = e // 获取微信昵称
			},
			async init(){
				const tkset= await this.$api.tkset();
				this.logo=tkset.data.img
				this.color=tkset.data.color
				this.titlecolor=tkset.data.titlecolor
				this.$u.vuex('tksetting', tkset.data)
			},
			async check_reg(){
				 const res=await this.$api.check_reg();
				 if(res.code==1){
					 
					 uni.showModal({
					 	title: '提示',
					 	content: '注册已经关闭,请联系管理员',
					 	success: function (res) {
					 		if (res.confirm) {
					 			uni.navigateBack();
					 		} else if (res.cancel) {
					 			uni.navigateBack();
					 		}
					 	}
					 });
					 
				 }
			},
			// 刷新验证码
			updateImageCode() {
			  this.mcaptcha.refresh()
			},
			async getarealist(){
				const res=await this.$api.arealist({t1:'label',t2:'id',all:''});
				if (res.code == 0) {
					this.arealist=[res.data];
					this.showarea=true;
				}
			},
			async getPhoneNumber (e) {
				console.log(e.detail)
				let that=this;
				let param = {
					sessionKey:that.session_ke,
					data:e.detail.encryptedData,
					iv:e.detail.iv
				}
				
				let data = await that.$api.jiemi(param);
				
				if(data.code==0){
					that.model1.userInfo.tel=data.data.phoneNumber;
				}else{
					toast("手机号获取错误,请关闭重试!")
				}
				
			},
			xieyi_check(n){
				//console.log(n.length)
				this.xieyi=n.length;
				
			},
			routs(id){
				useRouter('/pages/news/info',{id:id},'navigateTo')
			},
			navigateBack() {
				uni.navigateBack()
			},
			codeChange(text) {
				this.tips = text;
			},
			async getCode() {
				let tel=this.model1.userInfo.tel;
				if (this.$refs.uCode.canGetCode) {
						
					let validate = this.mcaptcha.validate(this.model1.userInfo.code);
						
					if(!validate){
						toast("请先填写验证码")
						return false;
					}
									
					const res= await this.$api.getcode({tel:tel,sign:'reg'})
					//console.log(res)
					if(res.code==0){
						toast(res.msg)
						this.$refs.uCode.start();
					}else{
						toast(res.msg)
					}
					
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			async submit() {
				
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				const _this=this;
				//console.log(this.model1.userInfo)
				if(!this.xieyi.length){
					toast('请先同意协议!')
					return false;
				}else{
				
				try{
					//this.model1.userInfo.xd_ewm=this.fileList1[0].url;
					//this.model1.userInfo.xd_pic=this.fileList2[0].url;	
				}catch(e){}
				console.log(this.model1)	
				const yz=await  _this.$refs.form1.validate().then(res => {
					return true;
				}).catch(errors => {
					uni.$u.toast('请将注册信息输入完整');
					return false
				})
				
				if(yz){
					this.model1.userInfo.mypid=this.mypid;
					this.ti_status=true;
					const ress= await  _this.$api.register(_this.model1.userInfo);
					//console.log(ress)
					if(ress.code==0){
						setStorageSync('token',_this.model1.userInfo.openid)
						_this.$u.vuex('userinfo',_this.model1.userInfo);
						setStorageSync('user_id', ress.data)
						uni.$u.toast(ress.msg)
						setTimeout(function(){
							useRouter('/pages/index/index',{},'reLaunch');
						},1000)
					}else{
						this.ti_status=false;
						uni.$u.toast(ress.msg)
					}
				}	
			}
			},
			
			hideKeyboard() {
				uni.hideKeyboard()
			},
			
			confirm(e) {
			    this.areaname=e.value[0].label;
				this.model1.userInfo.area=e.value[0].id;
				this.showarea=false;
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
				this.model1.userInfo.shopewm='';
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				let _this=this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url:BASE_URL + '/upload/upimg', // 仅为示例，非真实的接口地址
						filePath: url,
						name: "file",
						formData: {
							//token:getStorageSync('token')
						},
						success: (res) => {
							let shopewm=JSON.parse(res.data).data;
							resolve(shopewm)
						},
					});
				});
			},
		},
	}
</script>

<style lang="scss">
	
.u-page{
	padding: 40rpx;
}

</style>
